from django.shortcuts import render, redirect, HttpResponse
import json

# Create your views here.


from webadmin.views_dir import pub

from django.http import JsonResponse

import base64
import time
import os
from django.core.urlresolvers import reverse

from webadmin.views_dir.mongo_oper import get_db_obj

from django.views.decorators.csrf import csrf_exempt


class BaseResponse(object):
    def __init__(self):

        self.status = True
        self.message = None
        self.error = {}


@pub.is_login
def admin_index(request):
    return render(request, 'webadmin/base/index.html', locals())


# 登录
def login(request):

    response = BaseResponse()

    if request.method == "POST":
        username = request.POST.get('name')
        password = request.POST.get('password')

        result_user = get_db_obj().user.find_one({
            "username": username,
            "password": pub.str_encrypt(password)
        })

        if result_user:
            request.session['name'] = username
            request.session['user_id'] = result_user["_id"]
            request.session['is_login'] = True
            response.status = True
        else:
            response.status = False
            response.error['password'] = "用户名密码不对"

        return JsonResponse(response.__dict__)

    return render(request, 'webadmin/base/login.html', locals())


# 登出
def logout(request):
    request.session.clear()

    return redirect(reverse('login'))


# 密码管理
@pub.is_login
def password(request):
    response = pub.BaseResponse()
    user_id = request.session['user_id']

    if request.method == "POST":
        print(request.POST)
        oldPassword = request.POST.get('oldPassword')
        newPassword = request.POST.get('newPassword')
        rnewPassword = request.POST.get('rnewPassword')

        if not oldPassword.strip() or not newPassword.strip() or not rnewPassword.strip():
            response.statusCode = 300
            response.message = "密码不能为空"

        if not response.statusCode:
            if newPassword != rnewPassword:
                response.statusCode = 300
                response.message = "两次新密码不一致"

        if not response.statusCode:

            user_profile_obj = get_db_obj().user.find_one({
                "_id": user_id
            })
            print(user_profile_obj)
            # user_profile_obj = models.UserProfile.objects.get(id=user_id)
            if user_profile_obj["password"] != pub.str_encrypt(oldPassword):
                response.statusCode = 300
                response.message = "旧密码不正确,请重新输入"

            else:   # 旧密码正确
                user_profile_obj["password"] = pub.str_encrypt(newPassword)
                get_db_obj().user.update({"_id": user_id}, user_profile_obj)

                response.statusCode = 200
                response.message = "修改成功"

        return JsonResponse(response.__dict__)

    return render(request, 'webadmin/base/password.html')


# 图片上传
@csrf_exempt
@pub.is_login
def img_upLoad(request):

    response = pub.BaseResponse()

    img = request.FILES.get("editormd-image-file")
    img_name = img.name
    img_name = str(int(time.time() * 1000000)) + '.' + img_name.split('.')[-1]
    img_abs_name = os.path.join("statics", "upload_imgs",  img_name)

    with open(img_abs_name, "wb") as f:
        for chunk in img.chunks():
            f.write(chunk)

    result_data = {
        "success": 1,
        "url": "/" + img_abs_name
    }
    return HttpResponse(json.dumps(result_data))


@pub.is_login
def dwz_frag_xml(request):
    return render(request, "webadmin/base/dwx.frag.xml")
